#!/bin/bash

set -e

MYSQL_PWD='HB@p0s#2023_Secure!DB'
MYCNF1="/usr/local/etc/my.cnf"
MYCNF2="/opt/homebrew/etc/my.cnf"

echo "1. 停止 MySQL 服务..."
brew services stop mysql

echo "2. 用跳过权限表的方式启动 MySQL..."
if [ -x "/usr/local/opt/mysql/bin/mysqld_safe" ]; then
  /usr/local/opt/mysql/bin/mysqld_safe --skip-grant-tables > /tmp/mysql_reset.log 2>&1 &
elif [ -x "/opt/homebrew/opt/mysql/bin/mysqld_safe" ]; then
  /opt/homebrew/opt/mysql/bin/mysqld_safe --skip-grant-tables > /tmp/mysql_reset.log 2>&1 &
else
  mysqld_safe --skip-grant-tables > /tmp/mysql_reset.log 2>&1 &
fi

sleep 5

echo "3. 自动重置 root 密码..."
mysql -uroot <<EOF
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_PWD';
EOF

echo "4. 关闭所有 mysqld_safe 和 mysqld 进程..."
ps aux | grep mysqld | grep -v grep | awk '{print $2}' | xargs kill -9 || true
sleep 2

echo "5. 重启 MySQL 服务..."
brew services restart mysql
sleep 3

echo "6. 检查 3306 端口监听情况："
lsof -i :3306 || echo "❌ 3306端口未监听"

echo "7. 登录 MySQL 并输出关键信息："
mysql -uroot -p"$MYSQL_PWD" -e "SHOW VARIABLES LIKE 'port'; SHOW VARIABLES LIKE 'socket'; SHOW VARIABLES LIKE 'skip_networking';"

echo "全部操作完成！如有报错请截图发给助手。"